<?php

namespace App\Libs;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of WeChat
 *
 * @author guo
 */
use Log;
use DB;
use Cache;
use App\Libs\File;
use App\Libs\Weixin;
//use EasyWeChat\Message\Text;
use EasyWeChat\Message\News;
use EasyWeChat\Message\Image;

class WeChat {

    //put your code here
    public $expire;
    public $wechat;

    public function __construct() {
        $this->wechat = app('wechat');
        $this->expire = 60 * 1;  //  分钟
    }

    public function getWeChat() {
        return $this->wechat;
    }

    public function evcentHandle() {
        $this->wechat->server->setMessageHandler(function ($message) {
            switch ($message->MsgType) {
                case 'event':
                    return $this->eventHandle($message);
                case 'text':
                    return 'text';
                    return $this->textHandle($message);
                case 'image':
                    return $this->imageHandle();
                case 'voice':
                    return $this->voiceHandle();
                case 'video':
                    return $this->videoHandle();
                case 'location':
                    return $this->locationHandle();
                case 'link':
                    return $this->linkHandle();
                default:
                    return '到这了，还识别不了您发的是什么消息内容，我只能说，您稍等，马上有客服联系您的啦！！！';
            }
        });
    }

    public function eventHandle($message) {
        switch ($message->Event) {
            case 'subscribe':
                return $this->subscribeText();
            case 'CLICK':
                return $this->eventKeyHandle($message->EventKey);
            case 'unsubscribe':
                $this->unSubEvent();
            default:
                break;
        }
    }

    public function textHandle($message) {
        switch ($message->Content) {
            case "1":
                return "请点击 <a href='http://1zou.me/wechat/iconindex'>去看搭配</a>";
            case "2":
                return "请点击 <a href='http://1zou.me/wechat/iconindex'>去看搭配</a>";
            case "3":
                return "请点击 <a href='http://1zou.me/wechat/iconindex'>去看搭配</a>";
            case "4":
                return "请点击 <a href='http://1zou.me/wechat/iconindex'>去看搭配</a>";
            case "5":
                return "请点击 <a href='http://1zou.me/wechat/iconindex'>去看搭配</a>";
            case "红包雨":
                return "请加搭配师微信 13364300513，万搭微信号，既有整点红包雨。";
            default:
                break;
        }
//        return "请点击 <a href='http://1zou.me/wechat/iconindex'>去看搭配</a>";
    }

    public function imageHandle() {
        return "请到<a href='http://1zou.me/wechat/iconindex'>主页面</a>,进入衣服类型上传";
    }

    public function voiceHandle() {
        
    }

    public function locationHandle() {
        
    }

    public function linkHandle() {
        
    }

    public function eventKeyHandle($eventKey) {
        switch ($eventKey) {
            case 'help':
                return $this->helpMessage();
            case 'tips':
                return $this->tipsMessage();
//                return $this->getRandTips('tips');
            case 'talk':
                return $this->getTalk();
            default :
                break;
        }
    }

    public function helpMessage() {
        $news = new News([
            'title' => '有问题看这里，造型师来解答',
            'description' => '对于万搭有什么疑问和需要帮助的地方请戳这里！！！',
            'url' => 'http://mp.weixin.qq.com/s?__biz=MzI0MjIxNDYyNg==&mid=100000028&idx=1&sn=b6e3306f4abd98e99bddbe875d29f1dc',
            'image' => 'https://mmbiz.qlogo.cn/mmbiz/J9HvibiaDMkia0b3KkcKqWkjwrzicTDZxE4qoJh5a4QiczHmDW0k6ibJcurq19ibEpN1ReNQ80f2elrWTibhRu43fj2nbQ/0?wx_fmt=jpeg',
        ]);
        return $news;
    }

    public function tipsMessage() {
        $news1 = $this->helpMessage();
        $news2 = $this->subscribeMess();
        $news3 = $this->newestMess();
        return [$news3, $news1, $news2];
    }

    public function subscribeMess() {
        $news = new News([
            'title' => '万搭是什么--住在手机里面的专属造型师',
            'description' => '万搭内容介绍',
            'url' => 'http://mp.weixin.qq.com/s?__biz=MzI0MjIxNDYyNg==&mid=100000013&idx=1&sn=038b5e84e4e84862c018446ae916ba02',
            'image' => 'https://mmbiz.qlogo.cn/mmbiz/J9HvibiaDMkia2YWE45NXqzXOq23NLTPia5FwKzjLNFsRNH1fby2JrwgIPbsecnL2f75gqyaDiapKs2ibwmb1icTbP9rA/0?wx_fmt=jpeg',
        ]);
        return $news;
    }

    public function newestMess() {
        $news = new News([
            'title' => '一年穿三季| 这些经典单品你还没有？ 换季打折的时候就要买她们才叫精明购！',
            'description' => '不知不觉中就步入了8月，明明热成狗，逛街却满眼秋款上市，真是看一眼一身汗啊！不过呢，秋款上市必然伴随夏季打折，相信菇凉们一定不会错过这个机会狠狠地血拼！',
            'url' => 'http://mp.weixin.qq.com/s?__biz=MzI0MjIxNDYyNg==&mid=2247483887&idx=1&sn=a318c8f187cae0e90884ddd41a1bd279&scene=0#wechat_redirect',
            'image' => 'https://mmbiz.qlogo.cn/mmbiz/J9HvibiaDMkia3V23XsBbFp4k6r96Kibsp6ZicOrAxvBlzoQ3cibEbe0SOoVcTNiax8AQoiaQ6w2lYhPPnkibREEORFSicnA/0?wx_fmt=jpeg',
        ]);
        return $news;
    }

    public function subscribeImage() {
//        $image = new Image(['media_id' => '5q9I9r_E3OVFGWMKTH4QDMQNJJfFdvj9oqKOEjynpXU']);
        $image = new Image(['media_id' => '5q9I9r_E3OVFGWMKTH4QDJZMuQQVP3YyNI6hn66PMw4']);
        return $image;
    }

    public function subscribeText() {
        return $this->tipsText();
    }

    public function tipsText() {
        $text = "1. 万搭——电子衣橱+搭配师,<a href='http://1zou.me/wechat/iconindex'>永久免费放心用</a>  \n\n"
                . "2. <a href='http://1zou.me/wechat/iconindex'>真实用户衣橱</a>看搭配效果，满意亲再拍照去。1件or200件都是当天搭配好。\n\n"
                . "3. <a href='http://1zou.me/wechat/iconindex'>搭配每日都更新</a>，明星达人做示范。\n\n"
                . "4. 我是微信里的“轻APP”，<a href='http://1zou.me/wechat/iconindex'>点我拥有私人搭配师</a> \n\n";
        return $text;
    }

    public function unSubEvent() {
        
    }

    public function getButtons() {
        return [
            [
                "type" => "view",
                "name" => "入口",
                "url" => "http://1zou.me/apisq/wechatsq/test"
                ]
        ];

    }

    public function getButtons2() {
        return [
            [
                "type" => "view",
                "name" => "投票入口",
                "url" => "http://1zou.me/tools/vote/mon11"
            ]
        ];
    }

    public function callback() {
        $oauth = $this->wechat->oauth;
        $user = $oauth->user();
        Cache::put(session_id(), $user->toArray(), $this->expire);
        $targetUrl = Cache::get('target_url');
        Log::info('header ' . url($targetUrl));
        return redirect(url($targetUrl));
    }

    public function auth($url) {
        $oauth = $this->wechat->oauth;
        session_start();
        if (!Cache::has(session_id())) {
            Cache::put('target_url', $url, $this->expire);
            return $oauth->redirect();
        }
    }

    public function openid2id($user) {
        $wxUser = new Weixin;
        $wxUser->UserInfo($user->id);
        $userRow = DB::table('users')->where('weixinCode', $user->id)->first();
        if ($userRow->name === 'wx' || $userRow->name === 'wx2' || is_null($userRow->avatar)) {
            $wxUser->updateUserInfo($user->id, $user->nickname, $user->original['sex'], $user->avatar);
        }
        $itemCount = $this->getAllItemsNum($userRow->id);
        $id = $userRow->id;
        if ($itemCount === 0) {
//            $id = 89;
            $id = 1;
        }
        if ($userRow->id === 62) {
            $id = 1;
        }
        return $id;
    }

    public function getUserId($request) {   
        $user = (object) $request->session()->get('session_id');
        return $this->openid2id($user);
    }

    public function getRealUserId($request) {
        $user = (object) $request->session()->get('session_id');
        $userRow = DB::table('users')->where('weixinCode', $user->id)->first();
        return $userRow->id;
    }

    public function unicode2utf8_2($str) {
        $str = '{"result_str":"' . $str . '"}';
        $strarray = json_decode($str, true);
        return $strarray ['result_str'];
    }

    public function getAllItemsNum($userId) {
        $item = new ItemNormal;
        $tables = $item->getItemTables();
        $num = 0;
        foreach ($tables as $table) {
            $count = DB::table($table)->where('user_id', $userId)->count();
            $num = $num + $count;
        }
        return $num;
    }

    public function urlRequestArr($url) {
        $jsonStr = file_get_contents($url);
        $ress = json_decode($jsonStr, true);
        $datas = [];
        foreach ($ress as $itemArr) {
            array_push($datas, $itemArr);
        }
        return $datas;
    }

    public function downloadPic($mediaId, $folder) {
        $temporary = $this->wechat->material_temporary;
        $tempFile = File::fileUnique();
        if (File::directory($folder)) {
            $test = $temporary->download($mediaId, $folder . '/', $tempFile);
            Log::info($test);
        } else {
            die('no permisson');
        }
        return $folder . '/' . $tempFile . '.jpg';
    }

    public function limitCallOut($id, $times) {
        if (!Cache::has($id)) {
            Cache::put($id, 1, 60 * 24);
        } else if (Cache::get($id) < $times) {
            Cache::increment($id);
        } else {
            return true;
        }
        return false;
    }

    public function upload($path) {
        $material = $this->wechat->material;
        $result = $material->uploadImage($path);  // 请使用绝对路径写法！除非你正确的理解了相对路径（好多人是没理解对的）！
        Cache::put('mediaId ', $result->mediaId, 1);
//        unlink($path);
    }

    public function getRandTips($name) {
        $key = 'randRely_' . $name;
        if (!Cache::has($key)) {
            Cache::put($key, 0, 60 * 24 * 7);
        }
        switch (Cache::get($key) % 3) {
            case 0:
                $results = $this->tipsMessage();
                break;
            case 1:
                $results = $this->tipsText();
                break;
            case 2:
                $results = $this->subscribeImage();
                break;
        }
        Cache::increment($key);
        return $results;
    }

    public function getTalk() {
        return $this->tipsText();
    }
    
    public function isSubscribe($request) {
        $user = (object) $request->session()->get('session_id');
        $userService = $this->wechat->user;
        $openidUser = $userService->get($user->id);
        if($openidUser->subscribe === 1) {
            return true;
        }
        return false;
    }

}
